package com.hellojava.util;

import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.util.Util;
import com.hellojava.bean.OcrConstant;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * @author dengjihai
 * @create 2017-12-19
 **/
public class ImageOcr {

    static AipOcr client;

    static private Logger logger= LoggerFactory.getLogger(ImageOcr.class);


     static
     {
        client = new AipOcr(OcrConstant.APP_ID, OcrConstant.API_KEY, OcrConstant.SECRET_KEY);
         // 可选：设置网络连接参数
         client.setConnectionTimeoutInMillis(2000);
         client.setSocketTimeoutInMillis(60000);
     }


    /**
     * 通用文字识别
     * @param imgData 图片的字节流
     * @return
     */
    public static  JSONObject normalParse(byte[] imgData){
        JSONObject res = client.basicGeneral(imgData, new HashMap<String, String>());
        return res;
    }

    /**
     * 高精度识别图中文字
     * @param imgData 图片的字节流
     * @return
     */
    public static  JSONArray highParse(byte[] imgData){
        logger.info("\n ######开始解析图片ing....");
        long start =System.currentTimeMillis();
        JSONObject res = client.basicAccurateGeneral(imgData, new HashMap<String, String>());
        logger.info("百度返回：{}",res.toString());
        JSONArray jsonArray=res.getJSONArray("words_result");
        long end = System.currentTimeMillis();
        logger.info("\n #######总共解析花费时间:{}",(end-start),"毫秒");
        return jsonArray;
    }

    /**
     * 通用文字识别（含生僻字版）
     * @param imgData 图片的字节流
     * @return
     */
    public static  JSONArray enhancedParse(byte[] imgData){
        JSONObject res = client.basicAccurateGeneral(imgData, new HashMap<String, String>());
        JSONArray jsonArray=res.getJSONArray("words_result");
        return jsonArray;
    }


}
